$(function () {

    var initIndex = 2;

    getReviewers({});

    // 初始化页面上的 datetimepicker
    insDatetimePicker('.is-date');

    layui.use(['form', 'layer'], function () {
        var form = layui.form(),
            layer = layui.layer,
            currency = '￥';

        // 监听币种类型
        form.on('select(currency)', function (data) {
            if (data.value == '美元') {
                currency = '$';
                amountCalculation(currency);
                // 如果是美元就清空大写换算值
                $('.product-items-table tfoot tr:first-child td:last-child input').val('');
                // 当币种类型为美元得时候所有得含税变为"否"并重新进行渲染
                $('.product-items-table .tax').val('否');
            } else {
                currency = '￥';
                amountCalculation(currency);
                // 当币种类型为人民币得时候所有得含税变为"是"并重新进行渲染
                $('.product-items-table .tax').val('是');
            }
            form.render('select');
        });

        // 添加明细项
        $('#add-detail-item').click(function () {
            // 获取明细数量
            var item_qutatity = $(this).prev().find('tbody tr').length;
            // 去除最后一列合计的行
            item_qutatity = item_qutatity;

            var html = [
                '<tr>',
                    '<td class="valign-middle">'+ (item_qutatity + 1) +'</td>',
                    '<td class="valign-middle">',
                        '<input type="text" name="details['+ (initIndex) +'][pn]" lay-verify="required" class="layui-input">',
                    '</td>',
                    '<td class="valign-middle">',
                        '<input type="text" name="details['+ (initIndex) +'][desc]" lay-verify="required" class="layui-input">',
                    '</td>',
                    '<td class="valign-middle">',
                        '<input type="text" name="details['+ (initIndex) +'][unit_price]" lay-verify="required|money" class="layui-input listen unit-price">',
                    '</td>',
                    '<td class="valign-middle">',
                        '<input type="text" name="details['+ (initIndex) +'][qutatity]" lay-verify="required|number" class="layui-input listen qutatity">',
                    '</td>',
                    '<td class="valign-middle">',
                        '<input type="text" name="details['+ (initIndex) +'][pcs]" lay-verify="required" class="layui-input" value="个">',
                    '</td>',
                    '<td>',
                        '<input type="text" name="details['+ (initIndex) +'][total_amount]" readonly class="layui-input total-amount" style="cursor: not-allowed !important;">',
                    '</td>',
                    '<td class="valign-middle">',
                        '<select name="details['+ (initIndex) +'][tax]" class="tax">',
                            '<option value="是" selected>是</option>',
                            '<option value="否">否</option>',
                        '</select>',
                    '</td>',
                    '<td class="valign-middle">',
                        '<select name="details['+ (initIndex) +'][ed_protection]" class="ed-protection">',
                            '<option value="是" selected>是</option>',
                            '<option value="否">否</option>',
                        '</select>',
                    '</td>',
                    '<td class="valign-middle">',
                        '<button type="button" class="btn btn-danger btn-sm remove-product-detail-item">删除</button>',
                    '</td>',
                '</tr>'
            ].join('');

            $('.product-items-table tbody').append(html);
            initIndex++;

            // 添加明细后更新form组件避免出现无响应或渲染失败为空等现象
            form.render();
        });

        // 删除明细项
        $('.product-items-table').on('click', '.remove-product-detail-item', function () {
            var tr_len = $('.product-items-table tbody').children().length;
            // 当移除明细时检查是否小于 2 项，其中 1 项为合计栏位必须保留
            if (tr_len <= 1) {
                layer.msg('至少保留一项明细', {
                    icon: 0,
                    time: 2000
                });
            } else {
                $(this).parent().parent().remove();
                // 修正明细项删除后的序列错误
                $('.product-items-table tbody tr').each(function (index) {
                    $(this).find('td:first-child').text(index + 1);
                });
            }

            amountCalculation();
        });

        // 金额合计（横向）
        $(document).on('input propertychange', '.product-items-table .listen', function (e) {
            var tr = $(this).parent().parent(),
                unitPrice = parseFloat(tr.find('td:nth-child(4) input').val()),
                quantity = parseInt(tr.find('td:nth-child(5) input').val()),
                amount = ((unitPrice ? unitPrice : 0) * (quantity ? quantity : 0));

            var prefix = '￥';
            var currency = $('select.currency + .layui-form-select .layui-this').attr('lay-value');
            if (currency == '美元') prefix = '$';

            tr.find('td:nth-child(7) input').val(moneyFormat(amount, prefix));

            amountCalculation(prefix);
        });

        function amountCalculation(prefix) {
            // 计算纵向数量及金额
            var totalQuantity = 0, totalAmount = 0;
            $('.product-items-table tbody tr').each(function (index) {
                // 数量
                var curQuantity = $(this).find('td:nth-child(5) input').val();

                // 合计金额
                var amount = $(this).find('td:nth-child(7) input').val()

                // 切换币种时替换前缀
                $(this).find('td:nth-child(7) input').val(moneyFormat(moneyToNumber(amount), prefix));

                totalQuantity += parseInt(curQuantity ? curQuantity : 0);
                totalAmount += parseFloat(moneyToNumber($(this).find('td:nth-child(7) input').val()));
            });

            $('.product-items-table tfoot tr td:nth-child(2) input').val(totalQuantity);
            $('.product-items-table tfoot tr td:nth-child(4) input').val(moneyFormat(totalAmount, prefix));

            var currency = $('select.currency + .layui-form-select .layui-this').attr('lay-value');
            if (currency == '人民币') $('.product-items-table tfoot tr td:nth-child(5) input').val(Arabia_to_Chinese(totalAmount));
        }

        /*
                // 金额合计（纵向）
                $('.product-items-table').bind('input propertychange', '.total-amount', function () {
                    autoCalcTotalAmount();
                });

                function autoCalcTotalAmount() {
                    var total_amount = 0,
                        uppercase = '';
                    $('.product-items-table tbody tr .total-amount').each(function (index) {
                        // 保证值为数字的时候才进行计算，如果为非数字则 +0
                        console.log($(this).val());
                        var current_value = moneyToNumber($(this).val());
                        console.log(current_value);
                        total_amount += current_value ? parseFloat($(this).val()) : 0;
                    });
                    // 如果 total_amount 计算出的值为 NaN 则显示为空
                    if (total_amount) {
                        // 以千分位格式展现金额数值
                        var val = total_amount.toFixed(2) + ''; // 保留两位小数
                        val = val.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');
                        $('.product-items-table tbody tr:last-child td:nth-child(4)').text(currency + val);
                        // 当币种为人民币时才进行大写换算
                        if (currency == '￥') {
                            uppercase = Arabia_to_Chinese(total_amount);
                            $('.product-items-table tbody tr:last-child td:last-child').text(uppercase);
                        } else {
                            $('.product-items-table tbody tr:last-child td:last-child').text('');
                        }
                    } else {
                        $('.product-items-table tbody tr:last-child td:nth-child(4)').text('');
                        $('.product-items-table tbody tr:last-child td:last-child').text('');
                    }
                }
        */

    });

});